package com.yingpai.fitness.dvp_2_0.main.activity.dynamic;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.adpter.dynamic.DynamicCommentParentRecyclerAdapter;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.FeedBackActivity;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.CustomLinearLayoutManager;
import com.yingpai.fitness.dvp_2_0.main.widget.GlideImageLoader;
import com.yingpai.fitness.dvp_2_0.main.widget.MyBanner;
import com.yingpai.fitness.dvp_2_0.main.widget.ParentRecyclerView;
import com.yingpai.fitness.dvp_2_0.main.widget.RecyclerViewDivider;
import com.yingpai.fitness.entity.dynamic.DynamicBeanDetail;
import com.yingpai.fitness.entity.dynamic.DynamicCommentMoreBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.zzhoujay.richtext.RichText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;


public class DynamicDetailActivity extends CommonActivity implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.dynamic_detail_user_head_iv)
    CircleImageView dynamicDetailUserHeadIv;
    @BindView(R.id.dynamic_detail_user_head_name)
    TextView dynamicDetailUserHeadName;
    @BindView(R.id.dynamic_detail_user_follow_btn)
    TextView dynamicDetailUserFollowBtn;
    @BindView(R.id.dynamic_detail_user_upload_banner)
    MyBanner dynamicDetailUserUploadBanner;
    @BindView(R.id.dynamic_detail_user_brief_content)
    TextView dynamicDetailUserBriefContent;
    @BindView(R.id.dynamic_detail_user_location)
    TextView dynamicDetailUserLocation;
    @BindView(R.id.dynamic_detail_user_edit_date)
    TextView dynamicDetailUserEditDate;
    @BindView(R.id.comment_sum)
    TextView commentSum;
    @BindView(R.id.dynamic_detail_comment_rv_list)
    ParentRecyclerView dynamicDetailCommentRvList;
    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.dynamic_detail_comment_like_count_iv)
    ImageView dynamicDetailCommentLikeCountIv;
    @BindView(R.id.dynamic_detail_comment_like_count)
    TextView dynamicDetailCommentLikeCount;
    private DynamicCommentParentRecyclerAdapter mAdapter;//适配器
    private int id;
    private int pageNum = 1;
    private int pageSize = 5;
    private int index;
    private String flag;
    private int isPraised;
    private TokenBean tokenBean;
    private DynamicBeanDetail mDynamicBeanDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.dynamic_detail_activity);

    }

    private void requestMoreData() {
        showDialog(this, null);
        HttpParams httpParams = new HttpParams();
        httpParams.put("id", id);
        httpParams.put("myId", tokenBean.getId());
        httpParams.put("pageNum", pageNum++);
        httpParams.put("pageSize", pageSize);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_DYNAMIC_COMMENT_LIST, httpParams, Url.GET_DYNAMIC_COMMENT_LIST, new Callback<DynamicCommentMoreBean>() {
            @Override
            public void onSuccess(DynamicCommentMoreBean dynamicCommentMoreBean) {
                if (pageNum - 1 == 1) {
                    mAdapter.setNewData(dynamicCommentMoreBean.getMap().getPageInfo().getList());
                } else {
                    mAdapter.addData(dynamicCommentMoreBean.getMap().getPageInfo().getList());
                }

                mAdapter.notifyDataSetChanged();

                if (mAdapter.getData().size() >= dynamicCommentMoreBean.getMap().getPageInfo().getTotal()) {
                    mAdapter.loadMoreEnd();
                } else {
                    mAdapter.loadMoreComplete();
                    mAdapter.setEnableLoadMore(true);
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        //开始
        dynamicDetailUserUploadBanner.startAutoPlay();

    }

    @Override
    public void onStop() {
        super.onStop();
        //停止
        dynamicDetailUserUploadBanner.stopAutoPlay();

    }

    /**
     * 评论子控件监听
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
        switch (view.getId()) {

            case R.id.dynamic_comment_parent_user_apply:
                if (mDynamicBeanDetail.getMap().isPublisher()) {
                    index = position;
                    flag = "reply";
                    content.setHint("回复评论");
                    showSoftInputFromWindow(content);
                } else {
                    showToast("只有作者能回复");
                }

                break;
            case R.id.dynamic_comment_parent_user_like_count:
                index = position;
                HttpParams params = new HttpParams();
                params.put("customerId", tokenBean.getId());
                params.put("id", mAdapter.getItem(position).getId());
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.DYNAMIC_COMMENT_PRAISE, params, Url.DYNAMIC_COMMENT_PRAISE, new Callback<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse baseResponse) {
                        if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            mAdapter.getItem(position).setPraiseNo(mAdapter.getItem(position).getPraiseNo() + 1);
                            mAdapter.getItem(position).setIsPraised(1);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            showToast(baseResponse.getMsg());
                        }
                    }
                });
                break;

        }
    }


    public static void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager inputMethodManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(editText, 0);
    }

    public void hintEdit(EditText editText) {
        editText.setFocusable(false);
        editText.setFocusableInTouchMode(false);
        InputMethodManager inputMethodManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(String messageEvent) {
        if ("followed".equals(messageEvent)) {
            dynamicDetailUserFollowBtn.setText("已关注");
        } else if ("no_follow".equals(messageEvent)) {
            dynamicDetailUserFollowBtn.setText("关注");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void initView() {
        setTitle("动态详情");
        EventBus.getDefault().register(this);

        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            id = bundle.getInt("id", -1);
            isPraised = bundle.getInt("isPraised", -1);
        }

        dynamicDetailCommentRvList.setLayoutManager(new CustomLinearLayoutManager(getApplicationContext()));
        dynamicDetailCommentRvList.addItemDecoration(new RecyclerViewDivider(getApplicationContext(), LinearLayout.HORIZONTAL, 2, getApplicationContext().getResources().getColor(R.color.line_color_gray_dark)));
        mAdapter = new DynamicCommentParentRecyclerAdapter(R.layout.dynamic_comment_parent_list_item, this);
        dynamicDetailCommentRvList.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnLoadMoreListener(this);

        content.setFocusable(false);
        content.setFocusableInTouchMode(false);
    }

    @Override
    protected void initData() {
        showDialog(this, null);
        HttpParams params = new HttpParams();
        params.put("id", id);
        params.put("myId", tokenBean.getId());
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.DYNAMIC_DETAIL, params, Url.DYNAMIC_DETAIL, new Callback<DynamicBeanDetail>() {
            @Override
            public void onSuccess(DynamicBeanDetail dynamicBeanDetail) {
                if (dynamicBeanDetail.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    mDynamicBeanDetail = dynamicBeanDetail;
                    Glide.with(context)
                            .load(dynamicBeanDetail.getMap().getCustomerPhotoUrl())
                            .error(R.mipmap.icon_user_default)
                            .into(dynamicDetailUserHeadIv);

//                    dynamic_detail_title.setText(map.getTheme().getThemeTitle());
                    dynamicDetailUserHeadName.setText(dynamicBeanDetail.getMap().getTheme().getPublisherName());

                    if (dynamicBeanDetail.getMap().isFollowed()) {
                        dynamicDetailUserFollowBtn.setText("已关注");
                    } else {
                        dynamicDetailUserFollowBtn.setText("关注");
                    }
                    dynamicDetailUserUploadBanner.setImages(Arrays.asList(dynamicBeanDetail.getMap().getTheme().getPhotoUrls().split(",")))
                            .setImageLoader(new GlideImageLoader())
                            .start();

                    try {
                        commentSum.setText(dynamicBeanDetail.getMap().getPageInfo().getTotal() + " 全部评论");
                        mAdapter.setNewData(dynamicBeanDetail.getMap().getPageInfo().getList());
                    } catch (Exception e) {
                        commentSum.setText(0 + " 全部评论");
                        e.printStackTrace();
                    }
                    dynamicDetailUserLocation.setText(dynamicBeanDetail.getMap().getTheme().getPublishLocale());
                    dynamicDetailUserEditDate.setText(dynamicBeanDetail.getMap().getTheme().getPublishTime());
                    if (dynamicBeanDetail.getMap().getThemeDetail() != null && dynamicBeanDetail.getMap().getThemeDetail().size() != 0) {
                        RichText.fromHtml(dynamicBeanDetail.getMap().getThemeDetail().get(0).getDetailContent()).into(dynamicDetailUserBriefContent);
                    }
                    dynamicDetailCommentLikeCount.setText(dynamicBeanDetail.getMap().getTheme().getPraiseNo() + "");

                    if (isPraised == 0) {
                        dynamicDetailCommentLikeCountIv.setImageResource(R.mipmap.bbs_like_no);
                    } else {
                        dynamicDetailCommentLikeCountIv.setImageResource(R.mipmap.bbs_like);
                    }

                    content.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                        @Override
                        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                            if (actionId == EditorInfo.IME_ACTION_SEND && "comment".equals(flag)) {
                                if (!TextUtils.isEmpty(content.getText().toString().trim())) {
                                    showDialog(context, null);
                                    HttpParams httpParams = new HttpParams();
                                    httpParams.put("themeId", mDynamicBeanDetail.getMap().getTheme().getId());
                                    httpParams.put("customerId", tokenBean.getId());
                                    httpParams.put("content", content.getText().toString().trim());
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SAVE_DYNAMIC_COMMENT, httpParams, Url.SAVE_DYNAMIC_COMMENT, new Callback<BaseResponse>() {
                                        @Override
                                        public void onSuccess(BaseResponse baseResponse) {
                                            if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                pageNum = 1;
                                                requestMoreData();
                                                hintEdit(content);
                                            } else {
                                                showToast(baseResponse.getMsg());
                                            }
                                            dismissDialog();
                                        }
                                    });
                                    return true;
                                } else {
                                    showToast("内容不能为空");
                                }
                            } else if (actionId == EditorInfo.IME_ACTION_SEND && "reply".equals(flag)) {
                                if (!TextUtils.isEmpty(content.getText().toString().trim())) {
                                    showDialog(context, null);
                                    HttpParams httpParams1 = new HttpParams();
                                    httpParams1.put("id", mDynamicBeanDetail.getMap().getPageInfo().getList().get(index).getId());
                                    httpParams1.put("publisherReply", content.getText().toString().trim());
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SAVE_DYNAMIC_REPLY, httpParams1, Url.SAVE_DYNAMIC_REPLY, new Callback<BaseResponse>() {
                                        @Override
                                        public void onSuccess(BaseResponse baseResponse) {
                                            if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                mAdapter.getItem(index).setPublisherReply(content.getText().toString().trim());
                                                mAdapter.notifyDataSetChanged();
                                                hintEdit(content);
                                            } else {
                                                showToast(baseResponse.getMsg());
                                            }
                                            dismissDialog();
                                        }
                                    });
                                    return true;
                                } else {
                                    showToast("内容不能为空");
                                }
                            }
                            return false;
                        }
                    });
                } else {
                    showToast(dynamicBeanDetail.getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }


    @Override
    public void onLoadMoreRequested() {
        requestMoreData();
    }

    @Override
    @OnClick({R.id.dynamic_detail_user_head_iv, R.id.dynamic_detail_user_follow_btn, R.id.report, R.id.content, R.id.like_comment_rl})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.dynamic_detail_user_head_iv:
                Bundle bundle = new Bundle();
                bundle.putInt("id", mDynamicBeanDetail.getMap().getTheme().getPublisherId());
                startActivity(DynamicPersonalDetailActivity.class, bundle);
                break;
            case R.id.dynamic_detail_user_follow_btn:
                showDialog(this, null);
                HttpParams params = new HttpParams();
                params.put("myId", tokenBean.getId());
                params.put("otherId", mDynamicBeanDetail.getMap().getTheme().getPublisherId());
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.FOLLOW_OR_UNFOLLOW, params, Url.FOLLOW_OR_UNFOLLOW, new Callback<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse baseResponse) {
                        if (Constant.REQUEST_SUCCESS.equals(baseResponse.getResult())) {
                            if (mDynamicBeanDetail.getMap().isFollowed()) {
                                mDynamicBeanDetail.getMap().setFollowed(false);
                                dynamicDetailUserFollowBtn.setText("关注");
                            } else {
                                dynamicDetailUserFollowBtn.setText("已关注");
                                mDynamicBeanDetail.getMap().setFollowed(true);
                            }
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
                break;
            case R.id.report:
                Bundle bundle1 = new Bundle();
                bundle1.putString("title", mDynamicBeanDetail.getMap().getTheme().getThemeTitle());
                bundle1.putString("nikename", mDynamicBeanDetail.getMap().getTheme().getPublisherName());
                startActivity(FeedBackActivity.class, bundle1);
                break;
            case R.id.content:
                flag = "comment";
                content.setHint("回复作者，一起讨论");
                showSoftInputFromWindow(content);
                break;
            case R.id.like_comment_rl:
                if (isPraised == 0) {
                    showDialog(this, null);
                    dynamicDetailCommentLikeCountIv.setImageResource(R.mipmap.bbs_like);
                    dynamicDetailCommentLikeCount.setText(Integer.parseInt(dynamicDetailCommentLikeCount.getText().toString()) + 1 + "");
                    HttpParams httpParams = new HttpParams();
                    httpParams.put("customerId", tokenBean.getId());
                    httpParams.put("themeId", id);
                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.DYNAMIC_PRAISE, httpParams, Url.DYNAMIC_PRAISE, new Callback<BaseResponse>() {
                        @Override
                        public void onSuccess(BaseResponse baseResponse) {
                            if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                isPraised = 1;
                                EventBus.getDefault().post("点赞成功");
                            } else {
                                dynamicDetailCommentLikeCountIv.setImageResource(R.mipmap.bbs_like_no);
                                dynamicDetailCommentLikeCount.setText(Integer.parseInt(dynamicDetailCommentLikeCount.getText().toString()) - 1 + "");
                                showToast(baseResponse.getMsg());
                            }
                            dismissDialog();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                            dynamicDetailCommentLikeCountIv.setImageResource(R.mipmap.bbs_like_no);
                            dynamicDetailCommentLikeCount.setText(Integer.parseInt(dynamicDetailCommentLikeCount.getText().toString()) - 1 + "");
                        }
                    });
                } else {
                    showToast("您已经点过赞了");
                }
                break;
        }
    }
}
